from django.shortcuts import render
from django.http import HttpResponse
from .forms import PdfUploadForm
import PyPDF2


# Create your views here.
def pdf_extract(request):
    if request.method == 'POST':
        # 如果用户通过POST提交表单
        form = PdfUploadForm(request.POST, request.FILES)

        if form.is_valid():
            # 如果表单通过验证，获取提取文件页码
            page_num = int(request.POST.get('page'))
            # pdf文档页码对象编码是从0开始，所以要减去1
            page_index = page_num - 1
            # 获取上传的文件
            f = request.FILES['file']

            # 打开上传的文件，写入新的PDF文件
            with open('original.pdf', 'wb+') as pdfFileObj:
                for chunk in f.chunks():
                    pdfFileObj.write(chunk)
                # 利用PyPDF2读取新的PDF文件
                pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
                # 利用PyPDF2提取页码对象
                pageObj = pdfReader.getPage(page_index)
                # 利用PyPDF2创建新的PDF文件对象
                pdfWriter = PyPDF2.PdfFileWriter()
                # 添加已读取的页面对象
                pdfWriter.addPage(pageObj)
                # 将提取页面写入新的PDF文件
                with open('extracted_pages.pdf', 'wb') as pdfOutPutFile:
                    pdfWriter.write(pdfOutPutFile)
                # 打开新的PDF文件，通过HttpResponse输出
                with open('extracted_pages.pdf', 'rb') as pdfExtract:
                    response = HttpResponse(pdfExtract.read(), content_type='application/pdf')
                    response['Content-Disposition'] = 'attachment; filename="extracted_page_{}.pdf"'.format(page_num)
                    return response
    else:
        form = PdfUploadForm()
        return render(request, 'pdf/pdf_upload.html', {'form': form})
